package com.et.core.util

import android.os.Looper
import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import androidx.viewbinding.ViewBinding

const val ITEM_TYPE_GOODS = 100
const val ITEM_TYPE_FOOT = 200

class ViewHolderFoot(var binding: ViewBinding) :
    RecyclerView.ViewHolder(binding.root)


class AdapterFoot<M : Any>(
    var callFoot: (binding: ViewBinding) -> Unit,
    var callGoods: (binding: ViewBinding, m: M) -> Unit,
    var bindingFoot: (inflater: LayoutInflater, parent: ViewGroup) -> ViewBinding,
    var bindingGoods: (inflater: LayoutInflater, parent: ViewGroup) -> ViewBinding,
) :
    RecyclerView.Adapter<ViewHolderFoot>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolderFoot {
        if (viewType == ITEM_TYPE_FOOT) {
            return ViewHolderFoot(bindingFoot(LayoutInflater.from(parent.context), parent))
        }
        return ViewHolderFoot(bindingGoods(LayoutInflater.from(parent.context), parent))
    }


    private var data: MutableList<M>? = null

    fun dispatchUpdate(result: DiffUtil.DiffResult, dest: MutableList<M>) {
        android.os.Handler(Looper.getMainLooper()).let {
            it.post {
                result.dispatchUpdatesTo(this)
                data = dest
            }
        }
    }

    override fun onBindViewHolder(holder: ViewHolderFoot, position: Int) {
        if (holder.itemViewType == ITEM_TYPE_FOOT) {
            Log.d("et_log","ITEM_TYPE_FOOT")
            callFoot(holder.binding)
        } else {
            Log.d("et_log","ITEM_TYPE_GOODS")
            data?.let { callGoods(holder.binding, it[position]) }
        }
    }

    override fun getItemCount(): Int {
        return 1 + if (data == null) 0 else data!!.size
    }

    override fun getItemViewType(position: Int): Int {
        return if (position == if (data == null) 0 else data!!.size) return ITEM_TYPE_FOOT else ITEM_TYPE_GOODS
    }

}